package controller.listeners.manualCode;



import java.util.List;

import model.ManualCodeModel;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TableItem;

import view.ManualCodeView;

public class CacheCodeCorpsSelectionListener implements Listener {


	private ManualCodeView _view;
	private ManualCodeModel _model;
	
	
			public CacheCodeCorpsSelectionListener(ManualCodeView view,
					ManualCodeModel model) {
				this._model = model;
				this._view = view;
			}
			
			@Override
			public void handleEvent(Event event) {
				 
				
				
				
				if (event.detail == SWT.CHECK) {
					
					try {
						
						TableItem item = ((TableItem)event.item);
						
						if (_view.getSelected_cache_idcodecorp().size() <= 1) {
							//Si solo no hay varios seleccionados dejo seleccionado el checkeado
							int index = item.getParent().indexOf(item);
							_view.setSelected_cache_idcodecorp(index);
						}
						
						boolean ch = item.getChecked();
						//desmarco todo si estoy marcando el item
						//Para desmarcar no
						_view.checkAllCorps(false);
						_model.removeAllCheckedidcodedcorp();
						
						//vuelvo a marcar el item y todos los seleccionados
						_view.checkSelectedCorps(ch);
						item.setChecked(ch);
						
						int idcodecorp = Integer.parseInt(item.getText());
												
						if (item.getChecked()){
							_model.addCheckedidcodedcorp(idcodecorp);
							for (Integer idcodcorp: _view.getSelected_cache_idcodecorp())
								_model.addCheckedidcodedcorp(idcodcorp);
						} else {
							_model.removeCheckedidcodedcorp(idcodecorp);
							for (Integer idcodcorp: _view.getSelected_cache_idcodecorp())
								_model.removeCheckedidcodedcorp(idcodcorp);
						}
						
						_view.colourCacheCorpItem(item);
						 
					} catch (Exception e) {
						_view.checkSelectedCorps(false);
					}
				}
				List<Integer> idcodecorps = _view.getSelected_cache_idcodecorp();
			
				for (Integer id:idcodecorps)
					System.out.println(id);
				System.out.println("fin ids");
				_model.setSelected_cache_code_corp(idcodecorps);
				_view.setCandidateCenters(_model.getCandidateCenters(), _view.getSelected_cache_code_corp());
				
			}
		}